﻿using System;
using System.Collections.Generic;
using vHCS.RE.Business;
using vHCS.HR.Business;
using System.Data;
using Core.Message.Entities;
using Core.ExceptionHandling;
using Core.Controls.Message;
using Core.Common.Session;
using Telerik.Web.UI;
using vHCS.LS.Business;
using System.Configuration;
using System.Globalization;
using System.Web.UI.WebControls;

namespace vHCS.K2App.MdlK2.ResourceRequest.Ver1
{
    public partial class RE_ApprovalRequest : Core.NTier.UserInterface.BaseFormNotPer
    {
        #region Property
        protected string trvProChartClientId
        {
            get
            {
                try
                {
                    if (cboProChart.Items.Count > 0)
                    {
                        System.Web.UI.Control ctrlProchart = this.cboProChart.Items[0].FindControl("trvProChart");
                        return ctrlProchart.ClientID;
                    }

                }
                catch (Exception ex)
                {
                    AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                    MessageBox.Show(message);
                }
                return string.Empty;
            }
        }

        protected string trvMgtChartClientId
        {
            get
            {
                try
                {
                    if (cboMgtChart.Items.Count > 0)
                    {
                        System.Web.UI.Control ctrlMgtchart = this.cboMgtChart.Items[0].FindControl("trvMgtChart");
                        return ctrlMgtchart.ClientID;
                    }
                }
                catch (Exception ex)
                {
                    AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                    MessageBox.Show(message);
                }
                return string.Empty;
            }
        }
        /// <summary>
        /// Cơ cấu tổ chức
        /// </summary>
        public long OrgChart
        {
            set
            {
                this.cboOrgChart.Items[0].Value = string.Empty;
                this.cboOrgChart.Items[0].Text = string.Empty;
                this.cboOrgChart.SelectedIndex = 0;
            }
            get
            {
                long lId = 0;
                long.TryParse(this.cboOrgChart.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        #endregion
        private const string _REQUESTLIST = "~/MdlRE/RE_ApproveRequestList.aspx";
        //ROLE :  1: HRPP; 2: DeptHead; 3: Division Lead; 4: HR Head; 5: RRM 
        private string[] lst_CurrentApprove = new string[] { "HRBP", "Department Head", "Division Lead", "HR Head", "RRM" };
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    hdfSharedUser.Value = Request.QueryString["SharedUser"] != null ? Request.QueryString["SharedUser"].ToString() : "";
                    string sn = Request.QueryString["sn"] != null ? Request.QueryString["sn"].ToString() : "";
                    try
                    {
                        string requester = K2CoreLib.K2Utils.GetDataField(sn, "Requester", hdfSharedUser.Value);
                    }
                    catch (Exception ex)
                    {
                        btnApprove_Bot.Enabled = false;
                        btnApprove_Top.Enabled = false;
                        btnReject_Bot.Enabled = false;
                        btnReject_Top.Enabled = false;
                        //BusinessLogicCustomException ex = new BusinessLogicCustomException("12634");
                        throw ex;
                    }

                    this.hdfRequestID.Value = (Request.QueryString["RequestID"] == null) ? string.Empty : Request.QueryString["RequestID"].ToString().Trim();
                    //// Role của cấp phê duyệt kế tiếp
                    this.hdfRoleNext.Value = (Request.QueryString["RoleNext"] == null) ? string.Empty : Request.QueryString["RoleNext"].ToString().Trim();
                    this.hdfStatus.Value = (Request.QueryString["Status"] == null) ? string.Empty : Request.QueryString["Status"].ToString().Trim();
                    LoadFormForApprove(this.hdfRequestID.Value);
                    LoadRoleForApprove();
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        protected void btnList_Top_Click(object sender, EventArgs e)
        {
            Response.Redirect(_REQUESTLIST);
        }
        protected void btnApprove1_Click(object sender, EventArgs e)
        {
            try
            {
                string messCode = saveForApprove(1);
                if (messCode != "10162")// luu du lieu thanh cong
                    MessageBox.ShowByMessCode(messCode);
                else
                {
                    ExcuteK2("Approve");
                    ClientScript.RegisterStartupScript(Page.GetType(), "ClosePage", "ClosePage();", true);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        protected void btnReject_Click(object sender, EventArgs e)
        {
            try
            {
                string messCode = saveForApprove(2);
                if (messCode != "10162") // luu du lieu thanh cong
                    MessageBox.ShowByMessCode(messCode);
                else
                {
                    ExcuteK2("Reject");
                    ClientScript.RegisterStartupScript(Page.GetType(), "ClosePage", "ClosePage();", true);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        public void ExcuteK2(string approve)
        {
            try
            {
                K2Collection k2_col = new K2Collection();
                vHCS.SYS.Business.SYS_MailTemplateCollection col_mail = new vHCS.SYS.Business.SYS_MailTemplateCollection();
                SYS.Entities.SYS_MailTemplateDTO mail_dto = new SYS.Entities.SYS_MailTemplateDTO();
                RE_RequestCollection col_re = new RE_RequestCollection();
                string sn = Request.QueryString["sn"] != null ? Request.QueryString["sn"].ToString() : "";
                string requester = K2CoreLib.K2Utils.GetDataField(sn, "Requester", hdfSharedUser.Value);
                string DivID = K2CoreLib.K2Utils.GetDataField(sn, "DivID", hdfSharedUser.Value);
                string DeptID = K2CoreLib.K2Utils.GetDataField(sn, "DeptID", hdfSharedUser.Value);
                string DivName = K2CoreLib.K2Utils.GetDataField(sn, "DivName", hdfSharedUser.Value);
                string DeptName = K2CoreLib.K2Utils.GetDataField(sn, "DeptName", hdfSharedUser.Value);
                string ApproveDiv = "";
                string ApproveDept = "";
                string DtField_Approver = "";
                string status = Request.QueryString["RoleNext"] == null ? "" : Request.QueryString["RoleNext"].ToString();
                List<string> NextApprover = new List<string>();
                string Approver = "";
                string FieldMailApprove = "";
                LS_JobTitleBL bl_jobtitle = new LS_JobTitleBL();
                LS_JobTitleCollection cl_jobtitle = new LS_JobTitleCollection();
                bl_jobtitle = cl_jobtitle.SelectByID(Convert.ToInt64(cboChucvu.SelectedValue));
                string jobtitlename = "";
                string processid = col_re.SelectProcessID(hdfRequestID.Value);
                if (bl_jobtitle.DTO != null)
                    jobtitlename = bl_jobtitle.NameEN;

                //Lấy thông tin người phê duyệt kế tiếp và các thông tin cần lưu trữ trong datafield nếu status là Approve
                if (approve.Equals("Approve"))
                {
                    switch (status)
                    {
                        case "1": // HRB Activity
                            ApproveDept = k2_col.GetLeaderOfHierarchy(Convert.ToInt64(hdfDepartment_K2.Value));
                            ApproveDiv = k2_col.GetLeaderOfHierarchy(Convert.ToInt64(DivID));

                            NextApprover.Add("DeptHead");
                            NextApprover.Add(ApproveDept);
                            NextApprover.Add("Division");
                            NextApprover.Add(ApproveDiv);
                            NextApprover.Add("Budget");
                            NextApprover.Add(rdlBugdet.SelectedValue);

                            if (rdlBugdet.SelectedValue == "0") // Out budget
                            {
                                #region Gán thông tin gửi mail out budget
                                //Gán thông tin gửi mail
                                if (ApproveDept != ApproveDiv)
                                {
                                    mail_dto = col_mail.GetMailContentWithSignature("RE_K2_SendMailToDeptHead_RE_K2_DeptHead_OverBudget","K2-Signature");
                                    string MailContent = mail_dto.ContentVN;
                                    MailContent = MailContent.Replace("$Position$", jobtitlename);
                                    MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                    MailContent = MailContent.Replace("$Requestor$", requester);
                                    MailContent = MailContent.Replace("$Approver$", ApproveDept);
                                    MailContent = MailContent.Replace("$CurrentApprover$", SessionManager.UserDomain);
                                    MailContent = MailContent.Replace("$days$", "1 day");
                                    MailContent = MailContent.Replace("$headcount$", "headcount");
                                    MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                    MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));

                                    string MailSubject = mail_dto.TitleVN;
                                    MailSubject = MailSubject.Replace("$JobTitle$", jobtitlename);
                                    MailSubject = MailSubject.Replace("$Requestor$", requester);
                                    MailSubject = MailSubject.Replace("$Department$", DeptName);

                                    string MailDeptHead = col_mail.ReturnEmail(ApproveDept);
                                    string MailDivision = col_mail.ReturnEmail(ApproveDiv);

                                    NextApprover.Add("MailDeptHead");
                                    NextApprover.Add(MailDeptHead);
                                    NextApprover.Add("MailDivision");
                                    NextApprover.Add(MailDivision);
                                    NextApprover.Add("MailSubject_OutBudget");
                                    NextApprover.Add(MailSubject);
                                    NextApprover.Add("MailContent_OutBudget");
                                    NextApprover.Add(MailContent);
                                }
                                else
                                {   

                                    string MailContent = col_mail.ReturnMailContent("RE_K2_SendMailToDeptHead_RE_K2_DeptHead_OverBudget");
                                    MailContent = MailContent.Replace("$Position$", jobtitlename);
                                    MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                    MailContent = MailContent.Replace("$Requestor$", requester);
                                    MailContent = MailContent.Replace("$Approver$", ApproveDiv);
                                    MailContent = MailContent.Replace("$CurrentApprover$", SessionManager.UserDomain);
                                    MailContent = MailContent.Replace("$days$", "2 days");
                                    MailContent = MailContent.Replace("$headcount$", "staff cost/headcount");
                                    MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                    MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));

                                    string MailSubject = col_mail.ReturnSubjectMail("RE_K2_SendMailToDeptHead_RE_K2_DeptHead_OverBudget");
                                    MailSubject = MailSubject.Replace("$JobTitle$", jobtitlename);
                                    MailSubject = MailSubject.Replace("$Requestor$", requester);
                                    MailSubject = MailSubject.Replace("$Department$", DeptName);

                                    string MailDeptHead = col_mail.ReturnEmail(ApproveDept);
                                    string MailDivision = col_mail.ReturnEmail(ApproveDiv);

                                    NextApprover.Add("MailDeptHead");
                                    NextApprover.Add(MailDeptHead);
                                    NextApprover.Add("MailDivision");
                                    NextApprover.Add(MailDivision);
                                    NextApprover.Add("MailSubject_OutBudget");
                                    NextApprover.Add(MailSubject);
                                    NextApprover.Add("MailContent_OutBudget");
                                    NextApprover.Add(MailContent);
                                }
                                #endregion
                            }
                            else
                            {   // In budget
                                #region Gán thông tin gửi mail in budget
                                mail_dto = col_mail.GetMailContentWithSignature("RE_K2_SendMailToDeptHead_RE_K2_DeptHead_InBudget", "K2-Signature");
                                string MailContent = mail_dto.ContentVN;
                                MailContent = MailContent.Replace("$Position$", jobtitlename);
                                MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                MailContent = MailContent.Replace("$Requestor$", requester);
                                MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));
                                MailContent = MailContent.Replace("$DepartmentHead$", ApproveDept);

                                string MailSubject = mail_dto.TitleVN;
                                MailSubject = MailSubject.Replace("$JobTitle$", jobtitlename);
                                MailSubject = MailSubject.Replace("$Requestor$", requester);
                                MailSubject = MailSubject.Replace("$Department$", DeptName);
                                
                                string MailDeptHead = col_mail.ReturnEmail(ApproveDept);
                                string MailDivision = col_mail.ReturnEmail(ApproveDiv);

                                NextApprover.Add("MailDeptHead");
                                NextApprover.Add(MailDeptHead);
                                NextApprover.Add("MailDivision");
                                NextApprover.Add(MailDivision);
                                NextApprover.Add("MailSubject_OutBudget");
                                NextApprover.Add(MailSubject);
                                NextApprover.Add("MailContent_OutBudget");
                                NextApprover.Add(MailContent);
                                #endregion
                            }

                            break;
                        //
                        case "2": // DeptHead activity
                            //Gan user phe duyet Division/RRM (Out Budget/In Budget)
                            string Budget = K2CoreLib.K2Utils.GetDataField(sn, "Budget", hdfSharedUser.Value);

                            if (Budget == "0")
                            {
                                Approver = k2_col.GetLeaderOfHierarchy(Convert.ToInt64(DivID));
                                DtField_Approver = "Division";
                                FieldMailApprove = "MailDivision";

                                #region Gán thông tin gửi mail
                                //Gán thông tin gửi mail
                                mail_dto = col_mail.GetMailContentWithSignature("RE_K2_SendMailToDeptHead_RE_K2_DeptHead_OverBudget", "K2-Signature");
                                string MailContent = mail_dto.ContentVN;
                                MailContent = MailContent.Replace("$Position$", jobtitlename);
                                MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                MailContent = MailContent.Replace("$Requestor$", requester);
                                MailContent = MailContent.Replace("$Approver$", Approver);
                                MailContent = MailContent.Replace("$CurrentApprover$", SessionManager.UserDomain);
                                MailContent = MailContent.Replace("$days$", "2 days");
                                MailContent = MailContent.Replace("$headcount$", "staff cost/headcount");
                                MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));

                                string MailSubject = mail_dto.TitleVN;
                                MailSubject = MailSubject.Replace("$JobTitle$", jobtitlename);
                                MailSubject = MailSubject.Replace("$Requestor$", requester);
                                MailSubject = MailSubject.Replace("$Department$", DeptName);

                                string MailApprover = col_mail.ReturnEmail(Approver);
                                NextApprover.Add(FieldMailApprove);
                                NextApprover.Add(MailApprover);
                                NextApprover.Add("MailSubject_OutBudget");
                                NextApprover.Add(MailSubject);
                                NextApprover.Add("MailContent_OutBudget");
                                NextApprover.Add(MailContent);

                                #endregion
                            }
                            else
                            {
                                Approver = k2_col.GetUserRRM();
                                DtField_Approver = "RRM";
                                FieldMailApprove = "MailRRM";

                                #region Gán thông tin gửi mail RRM
                                mail_dto = col_mail.GetMailContentWithSignature("RE_K2_MailToRRM_InBudget", "K2-Signature");
                                string MailContent = mail_dto.ContentVN;
                                MailContent = MailContent.Replace("$Position$", jobtitlename);
                                MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                MailContent = MailContent.Replace("$Requestor$", requester);
                                MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));
                                MailContent = MailContent.Replace("$RecruitmentManager$", Approver);

                                string MailSubject = mail_dto.TitleVN;
                                MailSubject = MailSubject.Replace("$Title$", jobtitlename);
                                MailSubject = MailSubject.Replace("$Department$", DeptName);
                                MailSubject = MailSubject.Replace("$Requestor$", requester);

                                string MailApprover = col_mail.ReturnEmail(Approver);

                                NextApprover.Add(DtField_Approver);
                                NextApprover.Add(Approver);
                                NextApprover.Add(FieldMailApprove);
                                NextApprover.Add(MailApprover);
                                NextApprover.Add("MailSubject_ToRRM_InBudget");
                                NextApprover.Add(MailSubject);
                                NextApprover.Add("MailContent_ToRRM_InBudget");
                                NextApprover.Add(MailContent);
                                #endregion

                                #region Gán thông tin gửi mail Group RRM
                                DataTable dat = k2_col.GetValueK2ByCode("CCMAILRRM");
                                string mailGroupRRM = "";
                                foreach (DataRow row in dat.Rows)
                                {
                                    mailGroupRRM +=";" + row["value"].ToString();
                                }

                                if (!string.IsNullOrEmpty(mailGroupRRM))
                                {
                                    mail_dto = col_mail.GetMailContentWithSignature("RE_K2_MailToRRM_InBudget_Group", "K2-Signature");
                                    MailContent = mail_dto.ContentVN;
                                    MailContent = MailContent.Replace("$Position$", jobtitlename);
                                    MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                    MailContent = MailContent.Replace("$Requestor$", requester);
                                    MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                    MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("History_RERequest") + hdfRequestID.Value.Trim());
                                    MailContent = MailContent.Replace("$RecruitmentManager$", Approver);

                                    MailSubject = mail_dto.TitleVN;
                                    MailSubject = MailSubject.Replace("$Title$", jobtitlename);
                                    MailSubject = MailSubject.Replace("$Department$", DeptName);
                                    MailSubject = MailSubject.Replace("$Requestor$", requester);
                                    
                                    MailApprover = col_mail.ReturnEmail(Approver);

                                    NextApprover.Add("MailRRMGroup");
                                    NextApprover.Add(mailGroupRRM.Trim(';'));
                                    NextApprover.Add("MailSubject_RRMGroup");
                                    NextApprover.Add(MailSubject);
                                    NextApprover.Add("MailContent_RRMGroup");
                                    NextApprover.Add(MailContent);
                                }
                                #endregion
                            }

                            break;
                        case "3":   // Division Activity
                            NextApprover.Add("SendHRHead");
                            NextApprover.Add(rdlHRHead.SelectedValue);
                            if (rdlHRHead.SelectedValue == "1")
                            {
                                Approver = k2_col.GetUserOfHR();
                                NextApprover.Add("HRHead");
                                NextApprover.Add(Approver);
                                FieldMailApprove = "MailHRHead";

                                #region Gán thông tin gửi mail cho HR Head
                                //Gán thông tin gửi mai
                                mail_dto = col_mail.GetMailContentWithSignature("RE_K2_SendMailToDeptHead_RE_K2_DeptHead_OverBudget", "K2-Signature");
                                string MailContent = mail_dto.ContentVN;
                                MailContent = MailContent.Replace("$Position$", jobtitlename);
                                MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                MailContent = MailContent.Replace("$Requestor$", requester);
                                MailContent = MailContent.Replace("$Approver$", Approver);
                                MailContent = MailContent.Replace("$CurrentApprover$", SessionManager.UserDomain);
                                MailContent = MailContent.Replace("$days$", "2 days");
                                MailContent = MailContent.Replace("$headcount$", "headcount");
                                MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));

                                string MailSubject = mail_dto.TitleVN;
                                MailSubject = MailSubject.Replace("$JobTitle$", jobtitlename);
                                MailSubject = MailSubject.Replace("$Requestor$", requester);
                                MailSubject = MailSubject.Replace("$Department$", DeptName);

                                string MailApprover = col_mail.ReturnEmail(Approver);
                                NextApprover.Add(FieldMailApprove);
                                NextApprover.Add(MailApprover);
                                NextApprover.Add("MailSubject_OutBudget");
                                NextApprover.Add(MailSubject);
                                NextApprover.Add("MailContent_OutBudget");
                                NextApprover.Add(MailContent);

                                #endregion
                            }
                            else
                            {
                                Approver = k2_col.GetUserRRM();
                                NextApprover.Add("RRM");
                                NextApprover.Add(Approver);
                                FieldMailApprove = "MailRRM";

                                #region Gán thông tin gửi mail cho RRM
                                //Gán thông tin gửi mail
                                mail_dto = col_mail.GetMailContentWithSignature("RE_K2_MailToRRM_OutBudget", "K2-Signature");
                                string MailContent = mail_dto.ContentVN;
                                MailContent = MailContent.Replace("$Position$", jobtitlename);
                                MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                MailContent = MailContent.Replace("$Requestor$", requester);
                                MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));
                                MailContent = MailContent.Replace("$RecruitmentManager$", Approver);

                                string MailSubject = mail_dto.TitleVN;
                                MailSubject = MailSubject.Replace("$JobTitle$", jobtitlename);
                                MailSubject = MailSubject.Replace("$Requestor$", requester);
                                MailSubject = MailSubject.Replace("$Department$", DeptName);

                                string MailApprover = col_mail.ReturnEmail(Approver);
                                NextApprover.Add(FieldMailApprove);
                                NextApprover.Add(MailApprover);
                                NextApprover.Add("MailSubject_ToRRM_OutBudget");
                                NextApprover.Add(MailSubject);
                                NextApprover.Add("MailContent_ToRRM_OutBudget");
                                NextApprover.Add(MailContent);

                                #endregion

                                #region Gán thông tin gửi mail Group RRM
                                DataTable dat = k2_col.GetValueK2ByCode("CCMAILRRM");
                                string mailGroupRRM = "";
                                foreach (DataRow row in dat.Rows)
                                {
                                    mailGroupRRM += ";" + row["value"].ToString();
                                }

                                if (!string.IsNullOrEmpty(mailGroupRRM))
                                {
                                    mail_dto = col_mail.GetMailContentWithSignature("RE_K2_MailToRRM_OutBudget_Group", "K2-Signature");
                                    MailContent = mail_dto.ContentVN;
                                    MailContent = MailContent.Replace("$Position$", jobtitlename);
                                    MailContent = MailContent.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                    MailContent = MailContent.Replace("$Requestor$", requester);
                                    MailContent = MailContent.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                    MailContent = MailContent.Replace("$url$", ConfigurationManager.AppSettings.Get("History_RERequest") + hdfRequestID.Value.Trim());
                                    MailContent = MailContent.Replace("$RecruitmentManager$", Approver);

                                    MailSubject = mail_dto.TitleVN;
                                    MailSubject = MailSubject.Replace("$JobTitle$", jobtitlename);
                                    MailSubject = MailSubject.Replace("$Department$", DeptName);
                                    MailSubject = MailSubject.Replace("$Requestor$", requester);
                                    
                                    MailApprover = col_mail.ReturnEmail(Approver);

                                    NextApprover.Add("MailRRMGroup");
                                    NextApprover.Add(mailGroupRRM.Trim(';'));
                                    NextApprover.Add("MailSubject_RRMGroup");
                                    NextApprover.Add(MailSubject);
                                    NextApprover.Add("MailContent_RRMGroup");
                                    NextApprover.Add(MailContent);
                                }
                                #endregion
                            }

                            break;
                        case "4":   // HR Head Activity 
                            Approver = k2_col.GetUserRRM();
                            NextApprover.Add("RRM");
                            NextApprover.Add(Approver);
                            FieldMailApprove = "MailRRM";

                            #region Gán thông tin gửi mail
                            //Gán thông tin gửi mail
                            mail_dto = col_mail.GetMailContentWithSignature("RE_K2_MailToRRM_OutBudget", "K2-Signature");
                            string MailContentFin = mail_dto.ContentVN;
                            MailContentFin = MailContentFin.Replace("$Position$", jobtitlename);
                            MailContentFin = MailContentFin.Replace("$Dept/Div$", DeptName + "/" + DivName);
                            MailContentFin = MailContentFin.Replace("$Requestor$", requester);
                            MailContentFin = MailContentFin.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                            MailContentFin = MailContentFin.Replace("$url$", ConfigurationManager.AppSettings.Get("RecruitmentApprove"));
                            MailContentFin = MailContentFin.Replace("$RecruitmentManager$", Approver);

                            string MailSubjectFin = mail_dto.TitleVN;
                            MailSubjectFin = MailSubjectFin.Replace("$JobTitle$", jobtitlename);
                            MailSubjectFin = MailSubjectFin.Replace("$Requestor$", requester);
                            MailSubjectFin = MailSubjectFin.Replace("$Department$", DeptName);
                            
                            string MailApproverFin = col_mail.ReturnEmail(Approver);
                            NextApprover.Add(FieldMailApprove);
                            NextApprover.Add(MailApproverFin);
                            NextApprover.Add("MailSubject_ToRRM_OutBudget");
                            NextApprover.Add(MailSubjectFin);
                            NextApprover.Add("MailContent_ToRRM_OutBudget");
                            NextApprover.Add(MailContentFin);

                            #endregion

                            #region Gán thông tin gửi mail Group RRM
                            DataTable dat1 = k2_col.GetValueK2ByCode("CCMAILRRM");
                            string mailGroupRRM1 = "";
                            foreach (DataRow row in dat1.Rows)
                            {
                                mailGroupRRM1 += ";" + row["value"].ToString();
                            }

                            if (!string.IsNullOrEmpty(mailGroupRRM1))
                            {
                                mail_dto = col_mail.GetMailContentWithSignature("RE_K2_MailToRRM_OutBudget_Group", "K2-Signature");
                                MailContentFin = mail_dto.ContentVN;
                                MailContentFin = MailContentFin.Replace("$Position$", jobtitlename);
                                MailContentFin = MailContentFin.Replace("$Dept/Div$", DeptName + "/" + DivName);
                                MailContentFin = MailContentFin.Replace("$Requestor$", requester);
                                MailContentFin = MailContentFin.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                                MailContentFin = MailContentFin.Replace("$url$", ConfigurationManager.AppSettings.Get("History_RERequest") + hdfRequestID.Value.Trim());
                                MailContentFin = MailContentFin.Replace("$RecruitmentManager$", Approver);

                                MailSubjectFin = mail_dto.TitleVN;
                                MailSubjectFin = MailSubjectFin.Replace("$JobTitle$", jobtitlename);
                                MailSubjectFin = MailSubjectFin.Replace("$Department$", DeptName);
                                MailSubjectFin = MailSubjectFin.Replace("$Requestor$", requester);
                                

                                MailSubjectFin = col_mail.ReturnEmail(Approver);

                                NextApprover.Add("MailRRMGroup");
                                NextApprover.Add(mailGroupRRM1.Trim(';'));
                                NextApprover.Add("MailSubject_RRMGroup");
                                NextApprover.Add(MailSubjectFin);
                                NextApprover.Add("MailContent_RRMGroup");
                                NextApprover.Add(MailContentFin);
                            }
                            #endregion

                            break;
                        case "5":   // RRM Activity
                            #region Gán thông tin gửi mail cho Handle by
                            string MailContent_Handle = "";
                            string MailSubject_Handle = "";
                            string MailHandle = "";

                            string MailCC = "";
                            DataTable tablemail = k2_col.GetValueK2ByCode("CCMAILJOB");
                            if (tablemail != null && tablemail.Rows.Count > 0)
                            {
                                foreach (DataRow row in tablemail.Rows)
                                {
                                    MailCC += ";" + row["Value"];
                                }
                            }

                            mail_dto = col_mail.GetMailContentWithSignature("RE_K2_SendMail_HandleBy", "K2-Signature");

                            HR_EmpCVCollection empcv = new HR_EmpCVCollection();
                            string HandleByName = empcv.GetDisplayNameByUser(txtHandle.Text.Trim());
                            string RRMName = empcv.GetDisplayNameByUser(k2_col.GetUserRRM());

                            MailContent_Handle = mail_dto.ContentVN;
                            MailContent_Handle = MailContent_Handle.Replace("$Position$", jobtitlename);
                            MailContent_Handle = MailContent_Handle.Replace("$Number$", txtSoLuongTuyen.Value.ToString());
                            MailContent_Handle = MailContent_Handle.Replace("$Department$", DeptName);
                            MailContent_Handle = MailContent_Handle.Replace("$Division$", DivName);
                            MailContent_Handle = MailContent_Handle.Replace("$Requestor$", requester);
                            MailContent_Handle = MailContent_Handle.Replace("$url$", ConfigurationManager.AppSettings.Get("RE_HandleBy") + hdfRequestID.Value);
                            MailContent_Handle = MailContent_Handle.Replace("$Link$", ConfigurationManager.AppSettings.Get("RE_HandleBy") + hdfRequestID.Value);
                            MailContent_Handle = MailContent_Handle.Replace("$Recruiter$", txtHandle.Text.Trim());

                            MailSubject_Handle = mail_dto.TitleVN;
                            MailSubject_Handle = MailSubject_Handle.Replace("$Position$", jobtitlename);
                            MailSubject_Handle = MailSubject_Handle.Replace("$Dept$", DeptName);
                            

                            MailHandle = col_mail.ReturnEmail(txtHandle.Text.Trim());

                            NextApprover.Add("MailContent_Handle");
                            NextApprover.Add(MailContent_Handle);
                            NextApprover.Add("MailSubject_Handle");
                            NextApprover.Add(MailSubject_Handle);
                            NextApprover.Add("MailHandle");
                            NextApprover.Add(MailHandle);
                            if (!string.IsNullOrEmpty(MailCC))
                            {
                                NextApprover.Add("MailCC");
                                NextApprover.Add(MailCC.Trim(';'));
                            }
                            #endregion
                            break;
                    }
                }
                else //Gán thông tin khi người approver reject
                {
                    mail_dto = col_mail.GetMailContentWithSignature("RE_K2_MailReject", "K2-Signature");
                    string MailContent = mail_dto.ContentVN;
                    MailContent = MailContent.Replace("$Position$", jobtitlename);
                    MailContent = MailContent.Replace("$Department$", DeptName);
                    MailContent = MailContent.Replace("$Approver$", lst_CurrentApprove[Convert.ToInt16(hdfRoleNext.Value) - 1]);
                    MailContent = MailContent.Replace("$Comment$", txtComment.Text.Trim());
                    MailContent = MailContent.Replace("$Requestor$", requester);

                    string MailSubject = mail_dto.TitleVN;
                    MailSubject = MailSubject.Replace("$Position$", jobtitlename);
                    MailSubject = MailSubject.Replace("$Requestor$", requester);

                    string MailRequester = col_mail.ReturnEmail(requester);

                    NextApprover.Add("MailSubject_Reject");
                    NextApprover.Add(MailSubject);
                    NextApprover.Add("MailContent_Reject");
                    NextApprover.Add(MailContent);
                    NextApprover.Add("MailRequester");
                    NextApprover.Add(MailRequester);
                }
                //

                //Xử lý thực thi K2
                K2CoreLib.K2Utils.ActionExecute(sn, approve, hdfSharedUser.Value, NextApprover.ToArray());
                //Insert History Comment 
                K2CoreLib.K2Utils.InsertHistoryComment(processid, SessionManager.UserDomain);
                //

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void cboChucvu_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {

            try
            {
                long jobtitle = 0;
                long.TryParse(cboChucvu.SelectedValue, out jobtitle);

                if (jobtitle > 0)
                {
                    PopulateJobTitle(jobtitle);
                    //string mess = checkExistRequest(jobtitle);
                    //if (mess != "")
                    //{
                    //    SetComboValue(cboChucvu, "");
                    //    cboProChart.Items.Clear();
                    //    cboProChart.Items.Insert(0, new RadComboBoxItem("", ""));
                    //    cboProChart.SelectedIndex = 0;
                    //    MessageBox.ShowByMessCode(mess);
                    //}
                }
                else lblCanhBaoProChart.Visible = false;

                cboPCApply.DataBind();
                cboPCStandard.DataBind();
                SetComboPC();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }


        }
        protected void cboOrgChart_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                string orgChart = e.Value;
                char[] sep = { ';' };
                string[] temp = orgChart.Split(sep);
                if (sep.Length > 2)
                {
                    long valueDept = long.Parse(temp[2]);
                    string mess = checkExistRequest(valueDept);
                    if (mess != "")
                    {
                        SetComboValue(cboChucvu, "");
                        cboProChart.Items.Clear();
                        cboProChart.Items.Insert(0, new RadComboBoxItem("", ""));
                        cboProChart.SelectedIndex = 0;
                        MessageBox.ShowByMessCode(mess);
                    }
                }

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }

        }

        private string checkExistRequest(long jobTitle)
        {
            if (this.hdfDepartment.Value != "")
            {

                long detp = long.Parse(this.hdfDepartment.Value);
                RE_RequestCollection r = new RE_RequestCollection();
                DataTable t = r.CheckExistRequest(detp, jobTitle);
                if (t != null && t.Rows.Count > 0)
                {
                    return "12639";
                }

            }
            return "";
        }
        /// <summary>        
        /// Get combo Prochart và MgtChar theo jobtitle
        /// </summary>
        /// <param name="jobtitle">mã jobtitle</param>   
        /// 
        public void PopulateJobTitle(long jobtitle)
        {
            try
            {
                dtsProChart.SelectParameters["Jobtitle"].DefaultValue = jobtitle.ToString();
                dtsProChart.SelectParameters["prefix"].DefaultValue = "";
                RadTreeView treeviewpro = (RadTreeView)cboProChart.Items[0].FindControl("trvProChart");
                treeviewpro.DataBind();

                dtsMgtChart.SelectParameters["Jobtitle"].DefaultValue = jobtitle.ToString();
                RadTreeView treeviewmgt = (RadTreeView)cboMgtChart.Items[0].FindControl("trvMgtChart");
                treeviewmgt.DataBind();

                if (treeviewpro.IsEmpty & !string.IsNullOrEmpty(cboChucvu.SelectedValue))
                {
                    lblCanhBaoProChart.Visible = true;
                }
                else
                    lblCanhBaoProChart.Visible = false;

                dtsJobLevel.SelectParameters["jobtitle"].DefaultValue = jobtitle.ToString();
                dtsJobLevel.SelectParameters["p_strPrefix"].DefaultValue = "";
                cboCapbac.DataSourceID = dtsJobLevel.ID;
                cboCapbac.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        #region Functions
        /// <summary>
        /// Parse chuỗi cách nhau bởi dấu ";" thành mảng
        /// </summary>
        /// <param name="listid"></param>
        /// <returns></returns>
        public List<Int64> ParseItem(string listid)
        {
            List<Int64> result = new List<Int64>();
            try
            {
                string[] str_listid = listid.Split(';');
                foreach (string id in str_listid)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        result.Add(Convert.ToInt64(id));
                    }
                }
            }
            catch (Exception ex)
            {
                DataAccessExceptionHandler.HandleException(ex);
            }
            return result;
        }
        public RE_RequestBL addDataToObject()
        {
            RE_RequestBL jDes = new RE_RequestBL();

            try
            {
                HIE_EmpInHierarchyCollection cl_emphie = new HIE_EmpInHierarchyCollection();

                //** THÔNG TIN REQUEST
                jDes.RequestID = this.hdfRequestID.Value;
                jDes.LSJobTitleID = long.Parse(cboChucvu.SelectedValue);
                jDes.ReasonForRecruit = ushort.Parse(rdlLyDoTuyen.SelectedValue);
                if (rdlLyDoTuyen.SelectedValue != "1")
                    jDes.ReplaceFor = cboReplaceFor.SelectedValue;
                jDes.LSWorkingPlaceID = cboVanphonglamviec.SelectedValue != "" ? long.Parse(cboVanphonglamviec.SelectedValue) : 0;
                jDes.Gender = ushort.Parse(rdlGender.SelectedValue);
                jDes.JobType = ushort.Parse(rdlJobType.SelectedValue);
                jDes.ReportTo = cboReportTo.SelectedValue;
                if (cboTrinhDoHocVan.SelectedValue != "")
                    jDes.LSProfessionalLevelID = long.Parse(cboTrinhDoHocVan.SelectedValue); // Trinh độ học vấn
                if (txtSoLuongTuyen.Text != "")
                    jDes.Quantity = int.Parse(txtSoLuongTuyen.Text);

                jDes.JobLevel = Convert.ToInt64(cboCapbac.SelectedValue);

                //** THÔNG TIN REQUEST
                if (!string.IsNullOrEmpty(cboOrgChart.SelectedValue))
                {
                    jDes.LSDepartmentID = cl_emphie.SelectDeptHie(Convert.ToInt64(cboOrgChart.SelectedValue));
                    jDes.LSDivisionID = cl_emphie.SelectDivHie(Convert.ToInt64(cboOrgChart.SelectedValue));
                }
                else
                {
                    jDes.LSDepartmentID = Convert.ToInt64(string.IsNullOrEmpty(hdfDepartment.Value) ? "0" : hdfDepartment.Value);
                    jDes.LSDivisionID = cl_emphie.SelectDivHie(Convert.ToInt64(string.IsNullOrEmpty(hdfDepartment.Value) ? "0" : hdfDepartment.Value));
                }

                List<Int64> Projob = ParseItem(cboProChart.SelectedValue);

                if (Projob.Count > 0)
                    jDes.ProJobFamilyId = Projob[0];
                if (Projob.Count > 1)
                    jDes.ProJobGroupId = Projob[1];
                if (Projob.Count > 2)
                    jDes.ProSubGroupId = Projob[2];

                //MgtJob
                List<Int64> MgtJob = ParseItem(cboMgtChart.SelectedValue);
                if (MgtJob.Count > 0)
                    jDes.MgtJobFamilyId = MgtJob[0];
                if (MgtJob.Count > 1)
                    jDes.MgtJobGroupId = MgtJob[1];
                if (MgtJob.Count > 2)
                    jDes.MgtSubGroupId = MgtJob[2];

                jDes.JobDescriptionVN = txtMoTaTiengViet.Content;
                jDes.JobDescriptionEN = txtMoTaTiengAnh.Content;
                jDes.RequirementsVN = txtYeuCauTiengViet.Content;
                jDes.RequirementsEN = txtYeuCauTiengAnh.Content;
                jDes.PreferableVN = txtUuTienTiengViet.Content;
                jDes.PreferableEN = txtUuTienTiengAnh.Content;
                jDes.LSPositionClassStandard =hdfPCStandard.Value;
                jDes.LSPositionClassApply = Convert.ToInt64(string.IsNullOrEmpty(cboPCApply.SelectedValue)?"0":cboPCApply.SelectedValue);
                //** THÔNG TIN JOBDESCRIPTION
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return jDes;

        }
        private string saveRequest()
        {
            RE_ProcessHistoryCollection p = new RE_ProcessHistoryCollection();
            return p.SaveRequestK2(addDataToObject());
        }
        private string saveForApprove(int Status) // 1 approved , 2 reject
        {
            try
            {
                string messCode = "";
                if (this.hdfRoleNext.Value == "1")
                    messCode = saveRequest();
                if (messCode == "")
                {
                    RE_ProcessHistoryCollection p = new RE_ProcessHistoryCollection();
                    RE_ProcessHistoryBL bl = new RE_ProcessHistoryBL();
                    bl.RequestID = this.hdfRequestID.Value;
                    bl.Status = Status;
                    bl.ApproveDate = DateTime.Parse(dtpApproveDate.SelectedDate.ToString());
                    bl.ReceiveDate = DateTime.Parse(dtpReceiveDate.SelectedDate.ToString());
                    bl.Comments = txtComment.Text;

                    bl.InBugdet = this.rdlBugdet.SelectedValue == "1" ? true : false;

                    if (divHRHead.Style["display"] == "" && rdlHRHead != null)
                    {
                        bl.SendToHR = this.rdlHRHead.SelectedValue == "1" ? true : false;
                    }
                    if (cboOrgChart.SelectedValue == "")
                        bl.DepartmentID = long.Parse(this.hdfDepartment.Value);
                    else
                        bl.DepartmentID = this.OrgChart;

                    bl.Role = int.Parse(this.hdfRoleNext.Value);
                    if (divApproveInfo.Style["display"] == "")
                    {
                        bl.HandleBy = txtHandle.Text;
                        bl.Leadtime = LeadTimeEP.Value.ToString();
                        bl.LSDifficultLevelID = cboDiff.SelectedValue;
                        bl.LSPriorityID = cboPrio.SelectedValue;
                        bl.UnquieRole = this.rdlUnirole.SelectedValue == "1" ? true : false;
                    }
                    int currentHC = txtCurrentCount.Text != "" ? int.Parse(txtCurrentCount.Text) : 0;
                    messCode = p.SaveK2(bl, txtRequestCode.Text, currentHC);
                }
                return messCode;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void EnableControlRecruite()
        {

            cboChucvu.Enabled = true;
            cboTrinhDoHocVan.Enabled = true;
            cboProChart.Enabled = true;
            cboMgtChart.Enabled = true;
            txtMoTaTiengViet.EditModes = EditModes.Design;
            txtMoTaTiengAnh.EditModes = EditModes.Design;
            txtYeuCauTiengViet.EditModes = EditModes.Design;
            txtYeuCauTiengAnh.EditModes = EditModes.Design;
            txtUuTienTiengViet.EditModes = EditModes.Design;
            txtUuTienTiengAnh.EditModes = EditModes.Design;
            rdlLyDoTuyen.Enabled = true;
            cboReplaceFor.Enabled = true;
            txtSoLuongTuyen.Enabled = true;
            cboVanphonglamviec.Enabled = true;
            rdlGender.Enabled = true;
            rdlJobType.Enabled = true;
            cboReportTo.Enabled = true;
            cboPCApply.Enabled = true;
            cboPCStandard.Enabled = true;
            cboCapbac.Enabled = true;
        }

        private void LoadRoleForApprove()
        {
            RE_RequestCollection jDes = new RE_RequestCollection();
            long deptID = this.hdfDepartment.Value != "" ? long.Parse(this.hdfDepartment.Value) : 0;
            int Role = this.hdfRoleNext.Value != "" ? int.Parse(this.hdfRoleNext.Value) : 0;

            try
            {
                string status = this.hdfStatus.Value;
                string lblInfo = "";
                switch (this.hdfRoleNext.Value)
                {
                    case "1":
                        lblInfo = "HRBP: " + SessionManager.UserDomain;
                        divApproveInfo.Style.Add("display", "");// Thong tin approve
                        //divAddHRP.Style.Add("display", "");// Thong tin them cho HRP
                        //cboOrgChart.Enabled = true;
                        txtCurrentCount.Enabled = true;
                        txtCurrentCount1.Enabled = true;
                        rdlBugdet.Enabled = true;
                        EnableControlRecruite();  //hiển thị thong tin tuyen dung de chinh sua
                        EnableApprove(true);
                        lblGuide.Visible = true;
                        hplHRBPGuide.Visible = true;
                        cboPCStandard.Enabled = true;
                        break;
                    case "2":
                        lblInfo = "Department Head: " + SessionManager.UserDomain;
                        divApproveInfo.Style.Add("display", "");// Thong tin approve
                        EnableApprove(true);
                        lblGuide.Visible = true;
                        hplDeptGuide.Visible = true;
                        break;
                    case "3":
                        this.divHRHead.Style.Add("display", "");
                        lblInfo = "Division Lead: " + SessionManager.UserDomain;
                        divApproveInfo.Style.Add("display", "");// Thong tin approve
                        EnableApprove(true);
                        break;
                    case "4":
                        lblInfo = "RE Head: " + SessionManager.UserDomain;
                        divApproveInfo.Style.Add("display", "");// Thong tin approve
                        EnableApprove(true);
                        break;
                    case "5":
                        long dept = 0;
                        RE_ProcessHistoryCollection col = new RE_ProcessHistoryCollection();
                        if (cboOrgChart.SelectedValue == "")
                            dept = deptID;
                        else
                            dept = this.OrgChart;
                        if (dept > 0)
                            txtRequestCode.Text = col.genReqCode(dept);
                        this.ReqCode.Enabled = true;
                        this.ReqHandle.Enabled = true;
                        lblInfo = "RRM: " + SessionManager.UserDomain;
                        divApproveInfo.Style.Add("display", "");// Thong tin approve
                        divRRM.Style.Add("display", "");
                        EnableApprove(true);
                        break;
                    default:
                        EnableApprove(false);
                        break;
                }
                this.lblRoleInfo.Text = lblInfo;

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        private void EnableApprove(bool isApprove)
        {
            this.btnApprove_Top.Enabled = isApprove;
            this.btnApprove_Bot.Enabled = isApprove;
            this.btnReject_Top.Enabled = isApprove;
            this.btnReject_Bot.Enabled = isApprove;

        }
        private void setEmpy()
        {
            txtRequester.Text = "";
            txtRequesterRole.Text = "";
            txtBoPhan.Text = "";
            txtPhongBan.Text = "";
            txtNgayYeuCau.Text = "";
            txtNgayHiVong.Text = "";
            txtGhiChuClose.Value = "";
            this.hdfDepartment.Value = "";
            this.hdfStatus.Value = "";


            cboProChart.Items.Clear();
            cboProChart.Items.Insert(0, new RadComboBoxItem("", ""));
            cboProChart.SelectedIndex = 0;
            cboMgtChart.Items.Clear();
            cboMgtChart.Items.Insert(0, new RadComboBoxItem("", ""));
            cboMgtChart.SelectedIndex = 0;

            SetComboValue(cboTrinhDoHocVan, "");

            txtMoTaTiengAnh.Content = null;
            txtMoTaTiengViet.Content = null;
            txtUuTienTiengAnh.Content = null;
            txtUuTienTiengViet.Content = null;
            txtYeuCauTiengAnh.Content = null;
            txtYeuCauTiengViet.Content = null;
        }

        private void LoadFormForApprove(string requestID)
        {

            try
            {
                CultureInfo provider = CultureInfo.InvariantCulture;
                string format = "dd/MM/yyyy";
                RE_RequestCollection jDes = new RE_RequestCollection();

                DataTable tb = jDes.GetRequestForApprove(requestID);

                if (tb != null && tb.Rows.Count > 0)
                {
                    hdfDepartment_K2.Value = tb.Rows[0]["LSDepartmentID"].ToString();
                    hdfDivision_K2.Value = tb.Rows[0]["LSDivisionID"].ToString();

                    txtRequester.Text = tb.Rows[0]["RequesterID"].ToString();
                    txtRequesterRole.Text = tb.Rows[0]["TitleRequester"].ToString();
                    txtBoPhan.Text = tb.Rows[0]["BoPhan"].ToString();
                    txtPhongBan.Text = tb.Rows[0]["PhongBan"].ToString();
                    txtNgayYeuCau.Text = tb.Rows[0]["RequestDate"].ToString();
                    rdlLyDoTuyen.SelectedValue = tb.Rows[0]["LyDoTuyen"].ToString();
                    hdfRequestCode.Value = tb.Rows[0]["RequestCode"].ToString();

                    // ReceiDate là ngày nhận yeu cầu
                    this.dtpReceiveDate.SelectedDate = DateTime.ParseExact(tb.Rows[0]["ReceiveDate"].ToString(), format, provider);
                    this.dtpApproveDate.SelectedDate = DateTime.Now;

                    txtNgayHiVong.Text = tb.Rows[0]["ExpectedDate"].ToString();
                    txtGhiChuClose.Value = tb.Rows[0]["NoteRequestClose"].ToString();
                    this.hdfDepartment.Value = tb.Rows[0]["LSDepartmentID"].ToString();

                    // Load Current HeadCount
                    if (this.hdfDepartment.Value != "")
                    {
                        txtCurrentCount.Text = jDes.GetCurrentHC(int.Parse(this.hdfDepartment.Value), 1);
                        txtCurrentCount1.Text = jDes.GetCurrentHC(int.Parse(this.hdfDepartment.Value), 2);
                    }

                    this.hdfStatus.Value = tb.Rows[0]["Status"].ToString();
                    ////load jobTitle                    
                    //txtChucVu.Text = tb.Rows[0]["JobTitleName"].ToString();   

                    SetComboValue(cboChucvu, dtsJobTitle, "prefix", tb.Rows[0]["LSJobTitleID"].ToString());
                    PopulateJobTitle(long.Parse(tb.Rows[0]["LSJobTitleID"].ToString()));

                    dtsJobLevel.SelectParameters["p_strPrefix"].DefaultValue = "$SelectedValue$" + tb.Rows[0]["JobLevel"].ToString();
                    cboCapbac.DataBind();
                    SetComboValue(cboCapbac, tb.Rows[0]["JobLevel"].ToString(),true);

                    cboTrinhDoHocVan.DataBind();
                    cboTrinhDoHocVan.SelectedValue = tb.Rows[0]["LSProfessionalLevelID"].ToString();

                    //txtCoCauChuyenMon.Text = tb.Rows[0]["ProName"].ToString();
                    //txtCoCauQuanLy.Text = tb.Rows[0]["MgtName"].ToString();

                    this.hdfRequestID.Value = requestID;
                    string proSubGroupID = tb.Rows[0]["ProSubGroupId"].ToString();
                    string mgtSubGroupID = tb.Rows[0]["MgtSubGroupId"].ToString();
                    //Load cơ cấu chuyên môn            
                    RadTreeView treepro = (RadTreeView)cboProChart.Items[0].FindControl("trvProChart");
                    RadTreeView treemgt = (RadTreeView)cboMgtChart.Items[0].FindControl("trvMgtChart");
                    dtsProChart.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + proSubGroupID;
                    treepro.DataBind();

                    //Lấy HIERACHI của cơ cấu chuyên môn/Cơ cấu quản lý
                    DataTable orgChartList = jDes.SelectOrgChartName(requestID);

                    if (orgChartList != null && orgChartList.Rows.Count > 0)
                    {
                        //Gán cây cơ cấu chuyên môn
                        string prochartname = orgChartList.Rows[0]["ProName"].ToString();
                        cboProChart.Items.Clear();
                        RadComboBoxItem item_prochart = new RadComboBoxItem(prochartname, orgChartList.Rows[0]["ProJobID"].ToString());
                        cboProChart.Items.Insert(0, item_prochart);
                        cboProChart.SelectedIndex = 0;
                        rttProChart_input.Text = prochartname;

                        //Load lại cây cơ cấu quản lý
                        dtsMgtChart.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + mgtSubGroupID;
                        treemgt.DataBind();

                        //Gán cây cơ cấu quản lý
                        string mgtchartname = orgChartList.Rows[0]["MgtName"].ToString();
                        cboMgtChart.Items.Clear();
                        RadComboBoxItem item_mgtchart = new RadComboBoxItem(mgtchartname, orgChartList.Rows[0]["MgtJobID"].ToString());
                        cboMgtChart.Items.Insert(0, item_mgtchart);
                        cboMgtChart.SelectedIndex = 0;
                        rttMgtChart_Input.Text = mgtchartname;
                    }

                    txtMoTaTiengAnh.Content = tb.Rows[0]["MoTaTA"].ToString();
                    txtMoTaTiengViet.Content = tb.Rows[0]["MoTaTV"].ToString();
                    txtYeuCauTiengViet.Content = tb.Rows[0]["YeuCauTV"].ToString();
                    txtYeuCauTiengAnh.Content = tb.Rows[0]["YeuCauTA"].ToString();
                    txtUuTienTiengViet.Content = tb.Rows[0]["UuTienTV"].ToString();
                    txtUuTienTiengAnh.Content = tb.Rows[0]["UuTienTA"].ToString();



                    //txtReplaceFor.Text = tb.Rows[0]["ReplaceFor"].ToString();
                    dtsReplaceFor.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + tb.Rows[0]["ReplaceFor"].ToString();
                    cboReplaceFor.DataSourceID = dtsReplaceFor.ID;
                    cboReplaceFor.DataBind();
                    SetComboValue(cboReplaceFor, tb.Rows[0]["ReplaceFor"].ToString(), true);

                    txtSoLuongTuyen.Text = tb.Rows[0]["Quantity"].ToString();
                    cboVanphonglamviec.DataBind();
                    cboVanphonglamviec.SelectedValue = tb.Rows[0]["LSWorkingPlaceID"].ToString();
                    rdlGender.SelectedValue = tb.Rows[0]["GioiTinh"].ToString();
                    rdlJobType.SelectedValue = tb.Rows[0]["LoaiCV"].ToString();

                    dtsReportTo.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + tb.Rows[0]["ReportTo"].ToString();
                    cboReportTo.DataSourceID = dtsReportTo.ID;
                    cboReportTo.DataBind();
                    SetComboValue(cboReportTo, tb.Rows[0]["ReportTo"].ToString(), true);

                    //cboReportTo.SelectedValue = blRequest.ReportTo;
                    txtLeadTimeSD.Text = tb.Rows[0]["LeadTimeStandard"].ToString();

                    //------------------------------
                    //Gán cây cơ cấu tổ chức nếu có
                    string orgchartname = jDes.SelectOrgChartFullByReqID(hdfRequestID.Value);
                    cboOrgChart.Items.Clear();
                    RadComboBoxItem item_orgchart = new RadComboBoxItem(orgchartname, tb.Rows[0]["LSDepartmentID"].ToString());
                    cboOrgChart.Items.Insert(0, item_orgchart);
                    cboOrgChart.SelectedIndex = 0;
                    //------------------------------

                    dtsPCApply.SelectParameters["LSjoblevelID"].DefaultValue = tb.Rows[0]["JobLevel"].ToString();
                    //dtsPCStandard.SelectParameters["LSjoblevelID"].DefaultValue = tb.Rows[0]["JobLevel"].ToString();
                    cboPCApply.DataBind();
                    cboPCStandard.DataBind();
                    SetComboValue(cboPCApply, tb.Rows[0]["LSPositionClassApply"].ToString(), true);
                    //SetComboValue(cboPCStandard, tb.Rows[0]["LSPositionClassStandard"].ToString(), true);
                    SetValueComboPC(tb.Rows[0]["LSPositionClassStandard"].ToString());

                    //Load thông tin budget
                    rdlBugdet.SelectedValue = jDes.GetBudget(hdfRequestID.Value) == true ? "1" : "0";
                    //
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        #endregion

        /// <summary>
        /// Kiểm tra domain user có bị trùng không
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnVerify_click(object sender, EventArgs e)
        {
            try
            {
                RE_TasksCollection cl = new RE_TasksCollection();
                DataTable dat = new DataTable();
                string[] acc = txtHandle.Text.Split(new char[] { ';' });
                for (int i = 0; i < acc.Length; i++)
                {
                    if (!string.IsNullOrEmpty(acc[i]))
                    {
                        dat = cl.CheckExistsUser(acc[i]);
                        if (dat.Rows.Count < 1)
                        {
                            BusinessLogicCustomException ex = new BusinessLogicCustomException("12556");
                            ex.AdditionInfo = new String[] { acc[i] };
                            throw ex;
                        }
                    }

                }
                MessageBox.ShowByMessCode("12557");
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        public void SetValueComboPC(string PCID)
        {
            RE_RequestCollection col_request=new RE_RequestCollection();
            try
            {
                if (!string.IsNullOrEmpty(PCID.Trim(';')))
                {
                    string[] lstPC = PCID.Split(';');
                    foreach (string PC in lstPC)
                    {
                        foreach (RadComboBoxItem item in cboPCStandard.Items)
                        {
                            CheckBox chk = (CheckBox)item.FindControl("chkPC");
                            if (item.Value == PC)
                            {
                                chk.Checked = true;
                                break;
                            }
                        }
                    }

                    cboPCStandard.Items.Insert(cboPCStandard.Items.Count, new RadComboBoxItem(col_request.GetPCName(PCID), PCID));
                    cboPCStandard.SelectedIndex = cboPCStandard.Items.Count - 1;
                    cboPCStandard.Items[cboPCStandard.Items.Count - 1].Visible = false;

                    hdfPCStandard.Value = PCID;
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        public void SetComboPC()
        {
            try
            {
                //Gán thông tin PC
                string value = "";
                string text = "";
                foreach (RadComboBoxItem item in cboPCStandard.Items)
                {
                    CheckBox chk = (CheckBox)item.FindControl("chkPC");
                    chk.Checked = true;
                    value += ";" + item.Value;
                    text += ";" + item.Text;
                }

                cboPCStandard.Items.Insert(cboPCStandard.Items.Count, new RadComboBoxItem(text.Trim(';'), value.Trim(';')));
                cboPCStandard.SelectedIndex = cboPCStandard.Items.Count - 1;
                cboPCStandard.Items[cboPCStandard.Items.Count - 1].Visible = false;

                hdfPCStandard.Value = value;
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
    }
}